from tortoise.models import Model
from tortoise import fields
from pydantic import BaseModel, Field
from datetime import datetime
from enum import Enum
from typing import Optional  # 确保正确导入


# 订单状态枚举
class OrderStatus(str, Enum):
    PENDING = "pending"  # 待支付
    PAID = "paid"  # 已支付
    CANCELLED = "cancelled"  # 已取消
    REFUNDED = "refunded"  # 已退款


# Tortoise-ORM 模型
class Product(Model):
    product_id = fields.IntField(pk=True)  # 订单ID（主键）

    # 关联课程信息（非外键，存储快照）
    product_class_id = fields.IntField()  # 课程ID
    product_class_name = fields.CharField(max_length=100)  # 课程名称快照
    product_class_price = fields.DecimalField(max_digits=10, decimal_places=2)  # 价格快照

    # 订单元数据
    order_number = fields.CharField(max_length=50, unique=True)  # 订单编号
    status = fields.CharEnumField(OrderStatus, default=OrderStatus.PENDING)  # 订单状态
    created_at = fields.DatetimeField(auto_now_add=True)  # 创建时间
    paid_at = fields.DatetimeField(null=True)  # 支付时间

    # 多对一关系：多个订单属于一个用户
    student = fields.ForeignKeyField(
        "models.Student",
        related_name="orders",
        on_delete=fields.SET_NULL,  # 用户删除后保留订单记录
        null=True
    )

    class Meta:
        table = "products"
        indexes = [("order_number",), ("student_id",)]  # 订单编号和用户索引



    class Config:

        from_attributes = True